var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var MongoStore = require('connect-mongo')(session);
var settings = require('./settings');
var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;


var User = require('./models/User');

//路由控制
var routes = require('./routes/index');
var users = require('./routes/users');
var products = require('./routes/products');
var articles = require('./routes/articles');
var category = require('./routes/category');
var admin = require('./routes/admin');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});

passport.use('local', new LocalStrategy(
    function (username, password, done) {
        User.findOne({username: username, password: password}, function (err, user) {
            if (err) {
                return done(err);
            }
            if (!user) {
                return done(null, false, {message: '用户名/密码错误!'})
            }
            return done(null, user);
        });
    }
));

require('./models/db').connect(function (err, db) {
    if (err) {
        console.log(err);

    } else {
        console.log('连接数据库成功');
        db.close();
    }
});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '20mb', extended: true}));
app.use(cookieParser());
app.use(session({
    secret: settings.cookieSecret,
    resave: false,
    saveUninitialized: true,
    cookie: {maxAge: 3600000},
    store: new MongoStore({
        //host: settings.host,
        //db: settings.db,
        //port: settings.port
        url: settings.url
    })
}));
app.use(passport.initialize());
app.use(passport.session());


//静态目录
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'static')));

app.use('/', routes);
app.use('/users', users);
app.use('/products', products);
app.use('/articles', articles);
app.use('/admin', admin);
app.use('/category', category);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    res.render('404', {});
    //next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}


// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
